package com.cloud.auth.service;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.cloud.auth.domain.LoginReq;
import com.cloud.common.core.result.Result;
import com.cloud.common.satoken.core.domain.LoginUser;
import com.cloud.common.satoken.core.enums.DeviceType;
import com.cloud.common.satoken.util.LoginUtil;
import com.cloud.api.upms.feign.RemoteUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class LoginService {

	private final RemoteUserService remoteUserService;

	public Result<LoginUser> login(LoginReq loginReq) {
        Result<LoginUser> result = remoteUserService.info(loginReq.getUsername());
		if(result.iSuccess()){
			LoginUser userInfo = result.getData();
			if (!BCrypt.checkpw(loginReq.getPassword(), userInfo.getPassword())) {
				return Result.error("密码错误");
			}
			// 获取登录token
			StpUtil.checkDisable(userInfo.getLoginId());
			LoginUtil.loginByDevice(userInfo, DeviceType.PC);
			userInfo.setToken(StpUtil.getTokenValue());
			return Result.success(userInfo);
		}
		return Result.error(result==null?"登陆失败":result.getMsg());
	}

	public Result<LoginUser> smsLogin(String phone) {
        Result<LoginUser> result = remoteUserService.infoByPhone(phone);
        if(result.iSuccess()){
			LoginUser userInfo = result.getData();
			// 获取登录token
			LoginUtil.loginByDevice(userInfo, DeviceType.PC);
			userInfo.setToken(StpUtil.getTokenValue());
			return Result.success(userInfo);
		}
		return Result.error(result==null?"登陆失败":result.getMsg());
	}
	/**
	 * 退出登录
	 */
    public Result logout() {
		StpUtil.logout();
		return Result.success();
    }
}
